import datetime
from sre_constants import SUCCESS
from django.core.cache import cache
import json
from channels.generic.websocket import AsyncWebsocketConsumer

from app.views.DBUtils import DBUtil


chat_dist ={}

class ChatConsumer(AsyncWebsocketConsumer):
    

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.connected = False  # 增加一个标志来表示是否有连接进入


    async def  websocket_connect(self, message):
        """进入链接"""
        token  = self.scope['query_string'].decode()
        token = token.split("=")[1]
        if cache.get(token)!=None:
            await self.accept()
            chat_dist[cache.get(token)] = self
            data = {
                "type":"tip",
                "data":"OK"
            }
        else:
            data = {
                "type":"tip",
                "data":"请先登陆"
            }
        await self.send(json.dumps(data))

    async def receive(self, text_data):
        data_json = json.loads(text_data)
        openid = data_json.get("openid")
        id = data_json.get("id")
        message = data_json.get("message")
        ##先写到数据库里
        select_sql =f'''select 
                        send_openid,accept_openid 
                        from messagesinger
                        where parent_viewId = {id}
                    '''
        _,result =  DBUtil.execute_select(select_sql)
        result = result[0]
        if result[0] == openid:
            send_openid = result[0]
            accept_openid = result[1]
        else:
            send_openid = result[1]
            accept_openid = result[0]
        sql = f'''insert into messagesinger(send_openid,accept_openid,content,parent_viewId,create_time) values("{send_openid}","{accept_openid}","{message}",{id},"{datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")}")'''
        DBUtil.execute_insert_or_update(sql)
        if chat_dist.get(accept_openid):
            sql1 = """
                select m.id,m.send_openid,m.accept_openid,u1.nick_name as nick_name1,u2.nick_name as nick_name2,u1.img_url as img_url1,u2.img_url as img_url2,m.content,m.create_time 
                from messagesinger m 
                left join user u1 on m.send_openid = u1.openid 
                left join user u2 on m.accept_openid = u2.openid 
                where m.parent_viewId = {id}
                order by m.create_time desc limit 1 ;"""
            _,result = DBUtil.execute_select(sql1)
            result = [{"id":item[0],"send_openid":item[1],"accept_openid":item[2],"nick_name1":item[3],"nick_name2":item[4],"img_url1":item[5],"img_url2":item[6],"content":item[7]} for item  in result]
            data = {
                "type":"message",
                "data":result
            }
            chat_dist['accept_openid'].send(json.dumps(data))

    def websocket_disconnect(self, message):
        # 客户端向服务端断开连接时，自动触发
        print("连接断开！！")
        self.connected = False
